import socket
import time
import io
import torch
def receive_tensor(socket):
    # 首先读取数据长度
    data_length = int.from_bytes(socket.recv(4), byteorder='big')
    # 然后根据数据长度读取数据
    data = b''
    while len(data) < data_length:
        packet = socket.recv(data_length - len(data))
        if not packet:
            return None
        data += packet
    buffer = io.BytesIO(data)
    tensor = torch.load(buffer)
    return tensor

def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('', 9999)  # 空字符串表示监听所有可用的接口
    server_socket.bind(server_address)
    server_socket.listen(1)

    print("等待客户端连接...")
    connection, client_address = server_socket.accept()
    print(f"客户端 {client_address} 已连接")

    while True:
        # data = client_connection.recv(4)
        # if len(data) == 4:
        #     received_int = int.from_bytes(data, byteorder='big')
        #     print("---------",received_int)
        # else:
        #     print("Received incomplete data.")
        img = receive_tensor(connection)
        x = receive_tensor(connection)
        print("img.shape,x.shape---",img.shape, x.shape)

    connection.close()
    server_socket.close()

if __name__ == "__main__":
    main()
